package com.buobao.oa.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.function.Function;

/**
 * mybatis工具
 */
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object executeQuery(Function<SqlSession,Object> function){
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            Object result = function.apply(sqlSession);
            return result;
        } finally {
            if (sqlSession!=null) {
                sqlSession.close();
            }
        }
    }

    public static Object executeUpdate(Function<SqlSession,Object> function) {
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            Object result = function.apply(sqlSession);
            sqlSession.commit();
            return result;
        } catch (Exception e){
            sqlSession.rollback();
            throw  e;
        }finally {
            if (sqlSession!=null) {
                sqlSession.close();
            }
        }
    }
}
